package com.android.baseconfig.common.helper;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.config.HttpConstant;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author lei
 * @description OkHttp拦截器
 * @date 2018/1/24
 */

public class MyNetworkInterceptor implements Interceptor {
    public static String token;
    private final Context context;

    public MyNetworkInterceptor(Context context) {
        this.context = context;
    }


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder newRequestBuilder = chain.request().newBuilder();

        token = BaseSharedPreferences.getString(context, HttpConstant.TOKEN);
        if (!TextUtils.isEmpty(token)) {
            newRequestBuilder.addHeader(HttpConstant.COOKIE, token);
        }
        Response response = chain.proceed(newRequestBuilder.build());
        String cookies = response.header(HttpConstant.SET_COOKIE);

        if (!TextUtils.isEmpty(cookies)) {
            String str[] = cookies.split(";");
            for (String cookie : str) {
                if (cookie.startsWith("userId")) {
                    BaseSharedPreferences.setString(context, HttpConstant.TOKEN, str[0]);
                    Log.d("okhttp", "Response token :" + cookie);
                    break;
                }
            }
        }
        return response;
    }
}
